import fs from 'fs';
import path from 'path';
import DateUtils from '../utils/DateUtils.mjs';

/**
 * IO驱动类
 * @version 1.0.1
 */
class FsDriver {
    save(key, value) {
        fs.writeFileSync(key, value);
    }
    get(key, defaultValue = null, charset = 'utf-8') {
        return fs.existsSync(key) ? fs.readFileSync(key, { charset }) : defaultValue;
    }

    saveJSON(key, jsonValue) {
        fs.writeFileSync(key, JSON.stringify(jsonValue));
    }

    getJSON(filePath, defaultValue = null) {
        return fs.existsSync(filePath) ? JSON.parse(fs.readFileSync(filePath)) : defaultValue;
    }

    /**
     * 创建目录
     * @param {String} dirPath 目录或文件路径
     * @param {Boolean} isFile 是否文件，默认 false
     * @returns 
     */
    mkdir(dirPath, isFile = false) {
        if (isFile) {
            dirPath = path.dirname(dirPath);
        }
        if (fs.existsSync(dirPath)) {
            return;
        }
        fs.mkdirSync(dirPath, { recursive: true });
    }

    /**
     * 复制目录
     * @param {String} srcDir 
     * @param {String} destDir 
     * @example copyDir(fromDir, toDir, {
            filter: src => fs.statSync(src).isDirectory() || (fs.statSync(src).isFile() && path.basename(src).startsWith('order-'))
        });
     * @since Node v16.7.0
     * @link https://runebook.dev/en/articles/node/fs/fscpsrc-dest-options-callback
     */
    copyDir(srcDir, destDir, opt) {
        opt = Object.assign({ recursive: true, force: false }, opt ?? {})
        if (opt['filter'] != undefined && typeof (opt['filter']) != 'function') {
            delete opt.filter;
        }
        fs.cp(srcDir, destDir, opt, err => {
            if (err) {
                console.error('目录复制失败:', err);
            } else {
                // console.log('目录复制成功！');
            }
        })
    }

    log(filePath, message, isEcho = true) {
        message = (new DateUtils()).format('Y-m-d H:i:s ') + message;
        if (isEcho) {
            console.log(message);
        }
        fs.appendFileSync(filePath, message + '\n');
    }
}

export default FsDriver;